package create_tenant

import (
	"context"
	constants2 "git.mycaigou.com/gfyx/micro-gfyx-user-service/infrastructure/common/constants"
	"git.mycaigou.com/gfyx/micro-gfyx-user-service/infrastructure/repository/common"
	"gorm.io/gorm"
	"time"
)

type TenantsCreateTjLogRepository struct {
	common.TenantServiceDB
}

func NewTenantsCreateTjLogRepository() TenantsCreateTjLogRepositoryIface {
	return &TenantsCreateTjLogRepository{}
}

func (g *TenantsCreateTjLogRepository) AddTenantsCreateTjLog(ctx context.Context, data *TenantsCreateTjLog) (int32, error) {
	data.CreatedOn = time.Now()
	data.ModifiedOn = time.Now()
	err := g.GetTenantServiceDB(ctx).Create(&data).Error
	if err != nil {
		return 0, err
	}
	return data.Id, nil
}

func (g *TenantsCreateTjLogRepository) SaveTenantsCreateTjLog(ctx context.Context, data *TenantsCreateTjLog) error {
	data.ModifiedOn = time.Now()
	err := g.GetTenantServiceDB(ctx).Save(data).Error
	if err != nil {
		return err
	}
	return nil
}

func (g *TenantsCreateTjLogRepository) GetTenantsCreateTjLog(ctx context.Context, taskId string) (*TenantsCreateTjLog, error) {
	tenantsCreateTjLog := &TenantsCreateTjLog{}
	err := g.GetTenantServiceDB(ctx).
		Table(TenantsCreateTjLog{}.TableName()).
		Where("is_deleted = ?", constants2.IsDeletedFalse).
		Where("task_id = ?", taskId).
		Order("created_on desc").First(tenantsCreateTjLog).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return tenantsCreateTjLog, err
	}
	return tenantsCreateTjLog, nil
}

func (g *TenantsCreateTjLogRepository) UpdateResponseStatus(ctx context.Context, id int32, responseStatus int32, responseData string) (bool, error) {
	err := g.GetTenantServiceDB(ctx).
		Table(TenantsCreateTjLog{}.TableName()).
		Where("id=?", id).
		Where("is_deleted = ?", constants2.IsDeletedFalse).
		Updates(map[string]interface{}{"response_status": responseStatus, "response_data": responseData}).Error
	if err != nil {
		return false, err
	}
	return true, nil
}

func (g *TenantsCreateTjLogRepository) UpdateCallbackStatus(ctx context.Context, id int32, callbackRequest string, callbackResponse string) (bool, error) {
	err := g.GetTenantServiceDB(ctx).
		Table(TenantsCreateTjLog{}.TableName()).
		Where("id=?", id).
		Where("is_deleted = ?", constants2.IsDeletedFalse).
		Updates(map[string]interface{}{"callback_request": callbackRequest, "callback_response": callbackResponse}).Error
	if err != nil {
		return false, err
	}
	return true, nil
}
